package cn.zx.rmq.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @Package: cn.zx.rmq.consumer
 * @ClassName: PartialOrderConsumer
 * @Author: Think
 * @CreateTime: 2021/6/28 15:11
 * @Description:对同一客户ID的消息会单线程顺序地消费，如果有多个客户的消息，就会每个客户启动一个线程，进行单线程顺序地消费。
 * 即同一个客户的所有消息，会被某个固定的线程全部顺序消费，不会被其它线程消费，保证同一个客户消息消费的有序性。
 */
@Slf4j
public class PartialOrderConsumer {

    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("PartialOrderConsumer-Group");
        consumer.setNamesrvAddr("localhost:9876");
        consumer.subscribe("KYC", "about-order");
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                for (MessageExt msg : msgs) {
                    log.info("当前线程名称为：{}，获取的消息为：{}", Thread.currentThread().getName(), new String(msg.getBody()));
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });

        consumer.start();
        log.info("consumer started...");
    }

}
